package com.example.exercise;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.exercise.Base.SignBase;
import com.example.exercise.Base.User;
import com.example.exercise.MysqlUtil.DBService;
import com.example.exercise.Utils.GetNetWorkTime;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class SignRecord extends AppCompatActivity {

    private  TextView name,time,classroom,cardid,state;
    private ImageView serach,clear,tongji;
    private NfcAdapter mNfcAdapter;
    private PendingIntent pi;

    User user = new User();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_record);
        InitView();
        cardload();

        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (Integer.parseInt(GetNetWorkTime.getNetHour())<8){
                            Looper.prepare();
                            Toast.makeText(getApplicationContext(),"未到时间，不能清除",Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        }else {

                            Looper.prepare();
                            Inputpwd();
                            Looper.loop();
                        }
                    }
                }).start();


            }
        });

        tongji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), com.example.exercise.tongji.class);
                startActivity(intent);
            }
        });

        serach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                name.setText("");
                classroom.setText("");
                time.setText("");


                if (cardid.getText().toString().trim().equals("")){
                    Toast.makeText(getApplicationContext(),"卡号不能为空",Toast.LENGTH_SHORT).show();
                }
                else {

                    new Thread(new Runnable() {
                        @Override
                        public void run() {

                            final List<User> list = DBService.getUserName(cardid.getText().toString());
                            if (list.size() == 0){

                               runOnUiThread(new Runnable() {
                                   @Override
                                   public void run() {
                                       state.setText("读取失败，可能无卡号记录");
                                   }
                               });
                            }else {
                                user = list.get(0);
                                final List<SignBase> list1 = DBService.getUserSign(user.getName().toString());
                                SignBase signBase = new SignBase();
                                if (list1.size() == 0){
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    state.setText("读取失败，可能无签到记录");
                                                }
                                            });
                                        }
                                    });
                                }else{
                                    signBase = list1.get(0);
                                    final SignBase finalSignBase = signBase;

                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (finalSignBase.getTime().toString().equals("0")){

                                                state.setText("读取失败，可能无签到记录");
                                            }else {
                                                name.setText(finalSignBase.getName().toString());
                                                classroom.setText(finalSignBase.getClassroom().toString());
                                                time.setText(finalSignBase.getTime().toString());

                                            }

                                        }
                                    });
                                }


                            }


                        }
                    }).start();

                }

            }


        });
    }

    private void cardload() {

        //获取默认的NFC控制器
        //初始化NfcAdapter
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter == null) {
            Toast.makeText(getApplicationContext(), "设备不支持NFC!", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        if (!mNfcAdapter.isEnabled()) {
            Toast.makeText(getApplicationContext(), "请在系统设置中先启用NFC功能!", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        //初始化PendingIntent
        // 初始化PendingIntent，当有NFC设备连接上的时候，就交给当前Activity处理
        pi = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(), getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    }

    private void InitView() {

        tongji = findViewById(R.id.tongji);
        state = findViewById(R.id.textView81);
        name = findViewById(R.id.Signname1);
        time = findViewById(R.id.Signtime1);
        classroom = findViewById(R.id.Signclass1);
        cardid = findViewById(R.id.Signid1);
        serach = findViewById(R.id.load1);
        clear =  findViewById(R.id.load2);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 当前app正在前端界面运行，这个时候有intent发送过来，那么系统就会调用onNewIntent回调方法，将intent传送过来
        // 我们只需要在这里检验这个intent是否是NFC相关的intent，如果是，就调用处理方法
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
            processIntent(intent);
        }
    }

    //启动
    @Override
    protected void onResume() {
        super.onResume();
        mNfcAdapter.enableForegroundDispatch(this, pi, null, null);
    }

    //解析
    private void processIntent(Intent intent) {
        //取出封装在intent中的TAG
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        String CardId =ByteArrayToHexString(tagFromIntent.getId());
        cardid.setText(CardId);
        name.setText("");
        time.setText("");
        classroom.setText("");
        Toast.makeText(getApplicationContext(), CardId, Toast.LENGTH_LONG).show();
    }

    //转为16进制字符串
    private String ByteArrayToHexString(byte[] inarray) {
        int i, j, in;
        String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
                "B", "C", "D", "E", "F" };
        String out = "";


        for (j = 0; j < inarray.length; ++j) {
            in = (int) inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out += hex[i];
            i = in & 0x0f;
            out += hex[i];
        }
        return out;
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(newBase);

    }

    private void   Inputpwd() {
        /*@setView 装入一个EditView
         */

        final EditText editText = new EditText(SignRecord.this);
        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(SignRecord.this);
        inputDialog.setTitle("请输入还原密码").setView(editText);
        inputDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (editText.getText().toString().trim().equals("")){
                            Toast.makeText(getApplicationContext(),
                                    "输入为空，重新输入",
                                    Toast.LENGTH_SHORT).show();
                            Inputpwd();


                        }else {
                            if (editText.getText().toString().trim().equals("040722123456")){

                                showenter();

                            }
                            else {
                                Toast.makeText(getApplicationContext(),
                                        "密码错误",
                                        Toast.LENGTH_SHORT).show();
                                Inputpwd();
                            }
                        }
                    }
                }).show();


    }

    private void showenter() {

        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(SignRecord.this);
        normalDialog.setTitle("清除选择");
        normalDialog.setMessage("请选择清除无卡签到信息还是今日签到信息");
        normalDialog.setPositiveButton("无卡签到信息",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                if (DBService.delUserData("无卡") == 1){

                                    Looper.prepare();
                                    Toast.makeText(getApplicationContext(),"清除成功",Toast.LENGTH_SHORT).show();
                                    Looper.loop();
                                }
                                else {

                                    Looper.prepare();
                                    Toast.makeText(getApplicationContext(),"清除失败",Toast.LENGTH_SHORT).show();
                                    Looper.loop();
                                }
                            }
                        }).start();




                    }
                });
        normalDialog.setNegativeButton("今日签到所有信息",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        new Thread(new Runnable() {
                            @Override
                            public void run() {


                                if (DBService.Clear() == 1){

                                    Looper.prepare();
                                    Toast.makeText(getApplicationContext(),"清除成功",Toast.LENGTH_SHORT).show();
                                    Looper.loop();
                                }
                                else {

                                    Looper.prepare();
                                    Toast.makeText(getApplicationContext(),"清除失败",Toast.LENGTH_SHORT).show();
                                    Looper.loop();
                                }
                            }
                        }).start();

                    }
                });
        // 显示
        normalDialog.show();
    }
}